package admin

import (
	"context"
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"outsourced-projects/pkg/communal"
	"outsourced-projects/pkg/utils"
	"outsourced-projects/service"
	"time"
)

type Login struct {
	service.Base
}

func (login Login) Login(c *gin.Context) {
	var err error
	//数据获取
	jsondata := make(map[string]interface{})
	err = c.BindJSON(&jsondata)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	//初始化数据库
	db := communal.Sql()
	defer db.Close()

	accountStr := cast.ToString(jsondata["account"])

	d := []byte(fmt.Sprintf("vR8OS%s", jsondata["password"]))
	m := md5.New()
	m.Write(d)
	passwordStr := hex.EncodeToString(m.Sum(nil))

	user, err := db.QueryString(fmt.Sprintf("select * from `admin` where `status` = 0  and `account` = '%s' and `password` = '%s'", accountStr, passwordStr))
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}
	if len(user) <= 0 {
		service.ReturnJson(c, 500, errors.New("账号或密码错误").Error(), gin.H{})
		return
	}

	//jwt生成
	jwt, err := utils.GenerateWxToken(&utils.WxUserinfo{
		Id:  cast.ToInt(user[0]["id"]),
		Exp: time.Now().Add(86400 * time.Hour).Unix(),
	})
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	redisKey := fmt.Sprintf("outsourcedProjects:UserAccount:%d", cast.ToInt(user[0]["id"]))
	_, err = communal.Redis().Set(context.Background(), redisKey, jwt, time.Second*86400*30).Result()
	service.ReturnJson(c, 200, "获取成功", gin.H{
		"jwt": jwt,
	})
}

func (login Login) LoginOut(c *gin.Context) {
	var err error

	userid, ok := c.Get("userid")
	if !ok {
		service.ReturnJson(c, 500, errors.New("userid获取失败").Error(), gin.H{})
		return
	}

	//数据获取
	jsondata := make(map[string]interface{})
	err = c.BindJSON(&jsondata)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	redisKey := fmt.Sprintf("outsourcedProjects:UserAccount:%d", cast.ToInt(userid))
	_, err = communal.Redis().Del(context.Background(), redisKey).Result()

	service.ReturnJson(c, 200, "操作成功", gin.H{})
}

func (login Login) Me(c *gin.Context) {
	var err error

	userid, ok := c.Get("userid")
	if !ok {
		service.ReturnJson(c, 500, errors.New("userid获取失败").Error(), gin.H{})
		return
	}

	//数据获取
	jsondata := make(map[string]interface{})
	err = c.BindJSON(&jsondata)
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	//初始化数据库
	db := communal.Sql()
	defer db.Close()

	user, err := db.QueryString(fmt.Sprintf("select `id`,`nickname`,`account` from `admin` where `id` = %d", cast.ToInt(userid)))
	if err != nil {
		service.ReturnJson(c, 500, err.Error(), gin.H{})
		return
	}

	service.ReturnJson(c, 200, "操作成功", gin.H{
		"info": user[0],
	})
}
